import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../index.dart';

class CommonService extends GetxService {
  static CommonService get to => Get.find();

  // 添加评论
  Future<bool> addition_comment(
    String post_id,
    String content,
    UserModel current_user,
  ) async {
    try {
      // 创建新评论ID
      final comment_id = 'comment_${DateTime.now().millisecondsSinceEpoch}';

      // 创建评论模型
      final new_comment = CommentModel(
        comment_id: comment_id,
        comment_detail: content,
        user_id: current_user.id ?? '',
      );

      // 将评论保存到存储
      await Storage().set_json('comment_$comment_id', new_comment.toJson());

      // 更新评论ID列表
      final comment_ids = Storage().get_list(Constants.comment_list);
      if (!comment_ids.contains(comment_id)) {
        comment_ids.add(comment_id);
        await Storage().set_list(Constants.comment_list, comment_ids);
      }

      // 更新用户评论列表
      final user = UserService().get_user_data_by_id(current_user.id ?? '');
      if (user != null) {
        final updated_user = user.copyWith(
          comment_lists: [...?user.comment_lists, comment_id],
        );
        UserService().set_user(updated_user);
      }

      // 更新帖子的评论列表
      final all_posts = await PostService().get_all_posts();
      final post_index = all_posts.indexWhere((p) => p.post_id == post_id);

      if (post_index != -1) {
        final post = all_posts[post_index];
        List<String> updated_content_list = [
          ...post.post_content_list,
          comment_id,
        ];

        // 创建更新后的帖子
        final updated_post = post.copyWith(
          post_content_list: updated_content_list,
        );

        // 更新帖子
        await PostService().create_post(updated_post);
      }

      return true;
    } catch (e) {
      debugPrint('添加评论失败: $e');
      return false;
    }
  }

  // 根据id获取评论
  Future<CommentModel?> get_comment_by_id(String comment_id) async {
    final json = Storage().get_json("comment_$comment_id");
    return json != null ? CommentModel.fromJson(json) : null;
  }
}
